package org.yoyo.classroom.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yoyo.classroom.domain.po.Role;
import org.yoyo.classroom.result.Result;
import org.yoyo.classroom.service.RoleService;

import java.util.List;

/**
 * 角色控制器
 */
@RestController
@RequestMapping("/admin/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping
    public Result<List<Role>> getAllRoles() {
        List<Role> roles = roleService.getAllRoles();
        if (roles != null) {
            return Result.success(roles);
        } else {
            return Result.error("Failed to get roles");
        }
    }

    @GetMapping("/{id}")
    public Result<Role> getRoleById(@PathVariable Long id) {
        Role role = roleService.getRoleById(id);
        if (role != null) {
            return Result.success(role);
        } else {
            return Result.error("Role not found");
        }
    }

    @PostMapping
    public Result<String> addRole(@RequestBody Role role) {
        boolean isAdded = roleService.addRole(role);
        if (isAdded) {
            return Result.success("Role added successfully");
        } else {
            return Result.error("Failed to add role");
        }
    }

    @PutMapping("/{id}")
    public Result<String> updateRole(@PathVariable Long id, @RequestBody Role role) {
        role.setId(id);
        boolean isUpdated = roleService.updateRole(role);
        if (isUpdated) {
            return Result.success("Role updated successfully");
        } else {
            return Result.error("Failed to update role");
        }
    }

    @DeleteMapping("/{id}")
    public Result<String> deleteRole(@PathVariable Long id) {
        boolean isDeleted = roleService.deleteRole(id);
        if (isDeleted) {
            return Result.success("Role deleted successfully");
        } else {
            return Result.error("Failed to delete role");
        }
    }
}
